function syncSetTimeout(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

let config = {
    anmiUrl: "https://47.94.82.132:18001/",
    aiccyunUrl: "https://www.aigcyun.cn/",
    dashujuApi: "http://101.200.151.177:7000/monitor/callShop/overdueShopList",
    wsServer: "ws://jwx0904.x3322.net:18123"
}

let socketAiccyun = 0;
function connectAiccyun() {
    socketAiccyun = new WebSocket(config.wsServer);
    socketAiccyun.onopen = function(event) {
        socketAiccyun.send(JSON.stringify({
            origin: "aiccyun"
        }));
    };
    socketAiccyun.onmessage = (event) => {
        if (event.data === "1") return; 
        let message = JSON.parse(event.data);
        message.isGetData = true;
        if (message.to.includes("aiccyun")) {
            sendMessageToTab(message.toUrl, message);
        }
    };
    socketAiccyun.onclose = () => setTimeout(connectAiccyun, 2000);
}

let socketAnmi = 0;
function connectAnmi() {
    socketAnmi = new WebSocket(config.wsServer);
    socketAnmi.onopen = function(event) {
        socketAnmi.send(JSON.stringify({
            origin: "anmi"
        }));
    };
    socketAnmi.onmessage = (event) => {
        if (event.data === "1") return; 
        let message = JSON.parse(event.data);
        message.isGetData = true;
        if (message.to.includes("anmi")) {
            sendMessageToTab(message.toUrl, message);
        }
    };
    socketAnmi.onclose = () => setTimeout(connectAnmi, 2000);
}

function socketDisconnect() {
    // 断开所有WebSocket连接并不触发onclose事件
    if (socketAiccyun && socketAiccyun.close) {
        socketAiccyun.onclose = null; // 移除onclose处理函数
        socketAiccyun.close();
    }
    if (socketAnmi && socketAnmi.close) {
        socketAnmi.onclose = null; // 移除onclose处理函数
        socketAnmi.close();
    }
    socketAiccyun = 0;
    socketAnmi = 0;
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (!message.toUrl) return;
    console.log("getMessage", message.toUrl, message);
    if ((message.to === "background") && (message.toUrl === "background")) {
        if (message.title === "checkPayment") {
            checkPayment(message.data);
        } else if (message.title === "getUserPermission") {
            getUserPermission(message.data, message.from);
        } else if (message.title === "socketConnect") {
            let data = message.data;
            if (data === "aiccyun" && !socketAiccyun) {
                connectAiccyun();
            } else if (data === "anmi" && !socketAnmi) {
                connectAnmi();
            }
        } else if (message.title === "socketDisconnect") {
            socketDisconnect();
        }
        return;
    }
    sendMessageToTab(message.toUrl, message);
    if (socketAiccyun || socketAnmi) {
        if (message.to?.includes("anmi")) {
            socketAiccyun.send(JSON.stringify(message));
        } else if (message.to?.includes("aiccyun")) {
            socketAnmi.send(JSON.stringify(message));
        }
    }
    sendResponse({});
    return true;
});

function sendMessageToTab(toUrl, data) {
    toUrl.endsWith("/") ? (toUrl += "*") : (toUrl += "/*");
    chrome.tabs.query({ url: toUrl }, (tabs) => {
        if (tabs.length > 0) {
            const targetTab = tabs[0];
            console.log("sendMessage", data);
            chrome.tabs.sendMessage(
                targetTab.id,
                data
            );
        }
    });
}

// 查询合同结清状态
async function checkPayment(list) { 
    async function run(shop) {
        function getTodayDate() {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
            const day = String(today.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        const data = {
            pageNum: 1,
            pageSize: 10,
            shopId: shop.shopId,
            merId: "",
            shopName: "",
            overdueAmtStart: "",
            overdueAmtEnd: "",
            dpdStart: "",
            dpdEnd: "",
            rcTag: "",
            dtStart: getTodayDate(),
            dtEnd: getTodayDate(),
            distUser: ""
        };
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        };
        try {
            const response = await fetch(config.dashujuApi, requestOptions);
            if (!response.ok) {
                throw new Error('[collentionPlugin]checkPay -> 网络响应失败', response);
            }
            const result = await response.json();
            if (result.data.total) {
                shop.isPay = false;
            }
        } catch (error) {
            console.error('[collentionPlugin]checkPay -> 请求出错', error);
        }
    }
    for (let i = 0; i < list.length; i++) {
        const element = list[i];
        await syncSetTimeout(100);
        run(element);
    }
    await syncSetTimeout(1000);
    sendMessageToTab(config.anmiUrl, {
        from: "background",
        to: "anmi_checkPayment",
        toUrl: config.anmiUrl,
        title: "checkPayment",
        data: list
    });
}

async function getUserPermission(userName, to) {
    let level = "disabled";
    const control = await (await fetch('https://gitee.com/jokerbot/collection-plugin/raw/master/control.json')).json();
    if (control.available && control.user[userName]) {
        level = control.user[userName].level || "disabled";
    }
    let toUrl = to.includes("anmi") ? config.anmiUrl : to.includes("aiccyun") ? config.aiccyunUrl : "";
    sendMessageToTab(toUrl, {
        from: "background",
        to,
        toUrl,
        title: "getUserPermission",
        data: {
            level,
            assignment: control.assignment,
            available: control.available
        }
    });
}
